package com.jeremyfeinstein.utils;

import android.content.Context;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jeremyfeinstein.gson.OnResponse;
import com.jeremyfeinstein.gson.Tenant;
import com.jeremyfeinstein.okhttputil.OkHttpUtils;
import com.jeremyfeinstein.okhttputil.callback.FileCallBack;
import com.jeremyfeinstein.okhttputil.callback.StringCallback;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import nari.mip.core.Platform;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

public class YCHShttpAPI {
    private static final String TAG = YCHShttpAPI.class.getSimpleName();
    public static final int SUCCESS_CODE = 200;
    public static final int FAILURE_CODE = 400;
    public static final int SESSION_INVALID = 401;// session无效
    public static Gson gson;

    private static ExecutorService singlePool = Executors.newSingleThreadExecutor();

    /**
     * UAP平台的URL前缀
     */
    private static final String UAP_BASE_URL = "/sphsUap/sphsApp/rest/";

    public static String getCookiesString() {
        CookieJar cookieJar = OkHttpUtils.getInstance().getOkHttpClient()
                .cookieJar();
        HttpUrl arg0 = HttpUrl.parse(AppConstants.REQUEST_MODE + AppConstants.SERVER_URL);
        List<Cookie> cookies = cookieJar.loadForRequest(arg0);
        String cookieString = "";
        for (Cookie cookie : cookies) {
            cookieString += cookie.toString() + ";";
        }
        System.out.println("cookieString:" + cookieString);
        return cookieString;
    }

    public static void signSalt(Context context, StringCallback listener) {
        Map<String, String> params = new HashMap<>();
        params.put("flag", "1");
        post("/service/SignInSalt", params, context, listener);
    }


    public static void SignIn(Context context, String loginName,
                              String loginPsw, String salt, StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        params.put("loginName", loginName);
        params.put("loginPsw", loginPsw);
        // params.put("checkKey", salt);
        params.put("salt", salt);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        params.put("IMEI", tm.getDeviceId());
        params.put("IMSI", tm.getSubscriberId());

        post("/service/SignIn", params, context, stringCallback);
    }


    public static void SignIn(Context context, String loginName, String deviceIp,
                              StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String imsi = tm.getDeviceId();
        if (TextUtils.isEmpty(imsi)){
            imsi= Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        params.put("loginName", loginName);
        params.put("IMEI", imsi);
        params.put("IMSI", tm.getSubscriberId());
        params.put("requestIp", deviceIp);
        params.put("token", Platform.getCurrent().getMembership().getToken());

        post("Login/SignIn", params, context, stringCallback);
    }

    public static void LogOut(Context context, StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        post("Login/LogOut", params, context, stringCallback);
    }

    public static void KeepAlive(Context context, StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("sessiond", ConfigUtil.getInstance().getSessionId());
        post("/service/KeepAlive", params, context, stringCallback);
    }

    public static void GetMeetingList(Context context, String meetingLlistType,
                                      String page, String meetingName, StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("meetingLlistType", meetingLlistType);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        params.put("page", page);
        params.put("rowNum", "10");
        params.put("meetingName", meetingName);
        post("SphsApp/GetMeetingList", params, context, stringCallback);
    }

    public static void GetMeetingList(Context context, String meetingLlistType,
                                      String page, StringCallback stringCallback) {
        GetMeetingList(context, meetingLlistType, page, "", stringCallback);
    }

    public static void GetTempRoomStatus(Context context, String meetingId,
                                         StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("meetingId", meetingId);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        post("/service/GetTempRoom", params, context, stringCallback);
    }

    /**
     * 获取当前互动的附件列表
     *
     * @param context
     * @param meetingId
     * @param stringCallback
     */
    public static void GetMeetingFileList(Context context, String meetingId,
                                          StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("meetingId", meetingId);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());

        post("SphsApp/GetFileList", params, context, stringCallback);
    }

    public static void GetMeetingDetail(Context context, String meetingId,
                                        StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("meetingId", meetingId);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());

        post("SphsApp/GetMeetingDetail", params, context, stringCallback);
    }

    public static void GetMeetingUserList(Context context, String meetingId,
                                          StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("meetingId", meetingId);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());

        post("/service/GetMeetingUserList", params, context, stringCallback);
    }

    public static void CheckJoinMeeting(Context context, String url, String invite_code, String meetingId, String multiFlag, StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("meetingId", meetingId);
        params.put("invite_code", invite_code);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        params.put("multiFlag", multiFlag);

        //post(url, "/service/CheckJoinMeeting", params, context, stringCallback);
        post("SphsApp/CheckJoinMeeting", params, context, stringCallback);

    }


    public static void remoteSignIn(Context context, String meetingId,
                                    StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("meetingId", meetingId);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());

        post("SphsApp/remoteSignIn", params, context, stringCallback);
    }

    public static void createToken(Context context, String url, String username, String meetingId,
                                   String mcu_roomid, StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("role", "presenter");
        params.put("username", username);
        params.put("meetingId", meetingId);
        params.put("room", mcu_roomid);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());

        // post(url, "/service/MCU/createToken", params, context, stringCallback);
        post("SphsApp/MCU/createToken", params, context, stringCallback);

    }

    public static void deleteMeeting(Context context, String meetingId,
                                     StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("meetingId", meetingId);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());

        post("SphsApp/DeleteMeeting", params, context, stringCallback);
    }

    public static void getUserInfo(Context context,
                                   StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("sessionid", ConfigUtil.getInstance().getSessionId());

        post("SphsApp/GetUserInfo", params, context, stringCallback);
    }

    public static void getDepInfo(Context context, StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("sessionid", ConfigUtil.getInstance().getSessionId());

        post("SphsApp/GetDepInfo", params, context, stringCallback);
    }

    public static void signInSalt(Context context, StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();
//        params.put("sessionid", ConfigUtil.getApp().getSessionId());
        params.put("key", new String(ConferenceApp.getPubK()));
        post(false, "Login/SignInSalt", params, context, stringCallback);
    }


    public static void downloadFile(Context context, String fileId,
                                    StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();

        params.put("fileId", fileId);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());

        post("service/DownloadFile", params, context, stringCallback);
    }

    public static void meetingManager(Context context, String meetingId,
                                      String meetingName, String hostCode, String invite_code,
                                      String startTime, String endTime, String orgId, String agenda,
                                      int meetingResource, String assistantCode, int isRecord, String inviteUsers,
                                      int meetingType, String location, String numbers, String updateTime, String synNetwork, StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("meetingName", meetingName);
        params.put("hostCode", hostCode);
        params.put("invite_code", invite_code);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("orgId", orgId);
        params.put("agenda", agenda);
        params.put("meetingResource", String.valueOf(meetingResource));
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        params.put("inviteUsers", inviteUsers);
        params.put("meetingType", String.valueOf(meetingType));
        params.put("location", location);
        params.put("numbers", numbers);
        params.put("isRecord", String.valueOf(isRecord));
        params.put("synNetwork", synNetwork);
        params.put("updateTime", updateTime);
        if (!TextUtils.isEmpty(assistantCode)) {
            params.put("assistantCode", assistantCode);
        }
        if (!TextUtils.isEmpty(meetingId)) {
            params.put("meetingId", meetingId);
        }
        post("SphsApp/MeetingManager", params, context, stringCallback);
    }

    public static OnResponse getOnResponse(String response) {
        return new GsonBuilder().create().fromJson(response, OnResponse.class);

    }

    public static Tenant onResponse(String response) {
        return new GsonBuilder().create().fromJson(response, Tenant.class);
    }


    /**
     * get请求发送
     *
     * @param api            api接口名称
     * @param params         参数
     * @param stringCallback 回调
     */
    private static void get(String api, Map<String, String> params,
                            Context context, StringCallback stringCallback) {
        if (context == null)
            return;
        if (!Network.isAvailable(context)) {
            stringCallback.onError(null, 0, new Exception("当前无网络可用"));
            stringCallback.onAfter();
            return;
        }
        //  Log.d("GET:" + AppConstants.SERVER_URL + api, params.toString());
        OkHttpUtils.get()
                .url(AppConstants.SERVER_URL + api)
                .params(params)
                .buildByAESEncodeParams()
                .execute(stringCallback);
    }


    private static void post(String url, Map<String, String> params, StringCallback stringCallback) {
        if (!Network.isAvailable(ConferenceApp.getApp())) {
            stringCallback.onError(null, 0, new Exception("当前无网络可用"));
            stringCallback.onAfter();
            return;
        }
        if (params == null) {
            params = new HashMap<String, String>();
            params.put("param", "fill");// 占位参数，无用
        }
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .build()
                .execute(stringCallback);

    }

    private static void post(boolean isRSAEncode, String baseUrl, String api, Map<String, String> params,
                             Context context, StringCallback stringCallback) {
        postByCheckMipTimeOut(false, isRSAEncode, baseUrl, api, params, context, stringCallback);
    }

    /**
     * post请求发送
     *
     * @param api            api接口名称
     * @param params         参数
     * @param stringCallback 回调
     */
    private static void postByCheckMipTimeOut(boolean isCheckTimeOut, final boolean isRSAEncode, final String baseUrl,
                                              final String api, Map<String, String> params,
                                              final Context context, final StringCallback stringCallback) {


        if (context == null)
            return;

        if (!Network.isAvailable(context)) {
            stringCallback.onError(null, 0, new Exception("当前无网络可用"));
            stringCallback.onAfter();
            return;
        }

        if (params == null) {
            params = new HashMap<String, String>();
        }
        params.put("param", "fill");// 占位参数，无用
        params.put("time", DateFormatUtil.getCurrentDate());
//        Map<String, String> requestParam = encryptRequestParam(params);

        postByEncode(isRSAEncode, baseUrl, api, params, stringCallback);
    }

    private static void postByEncode(boolean isRSAEncode, String baseUrl, String api, Map<String, String> params, StringCallback stringCallback) {
        AppConstants.SERVER_URL = SPUtil.get(AppConstants.UAP_URL, "").toString();

      /*  Map<String, String> requestParam = encryptRequestParam(params);
        if (requestParam == null) {
            stringCallback.onError(null, -2, new Exception("参数为空"));
            return;
        }*/

//        Log.d(TAG, "POST: " + ((TextUtils.isEmpty(baseUrl) ? AppConstants.SERVER_URL + UAP_BASE_URL + api : baseUrl + api)) + params.toString());
        String url = TextUtils.isEmpty(baseUrl) ? AppConstants.SERVER_URL + UAP_BASE_URL + api : baseUrl + api;
        String url1 = url.startsWith("https") ? url.replace("https", "http") : url;
        if (isRSAEncode) {
            OkHttpUtils.post()
                    .url(url)
//                    .url("http://192.168.31.229:9001" + UAP_BASE_URL + api)
                    .params(params)
                    .buildByAESEncodeParams()
                    .execute(stringCallback);
        } else {
            OkHttpUtils.post()
                    .url(url)
//                    .url("http://192.168.31.229:9001" + UAP_BASE_URL + api)
                    .params(params)
                    .build()
                    .execute(stringCallback);
        }
    }

    private static void post(boolean isRSAEncode, String api, Map<String, String> params,
                             Context context, StringCallback stringCallback) {
        post(isRSAEncode, "", api, params, context, stringCallback);
    }

    /**
     * post请求发送
     *
     * @param api            api接口名称
     * @param params         参数
     * @param stringCallback 回调
     */
    private static void post(String api, Map<String, String> params,
                             Context context, StringCallback stringCallback) {
        post(true, "", api, params, context, stringCallback);
    }

    /**
     * 上传文件
     *
     * @param context      上下文
     * @param eventId      互动id
     * @param fileCallback 回调
     */
    public static void postFile(Context context, String eventId, File uploadFile, StringCallback fileCallback) {
        if (context == null)
            return;

        if (!Network.isAvailable(context)) {
            fileCallback.onError(null, 0, new Exception("当前无网络可用"));
            fileCallback.onAfter();
            return;
        }
        Map<String, String> params = new HashMap<String, String>();
        params.put("eventId", eventId);// 占位参数，无用
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        params.put("time", DateFormatUtil.getCurrentDate());
//        Map<String, String> requestParam = encryptRequestParam(params);
//        if (requestParam == null) {
//            fileCallback.onError(null, -2, new Exception("参数为空"));
//            return;
//        }

        String filePath = uploadFile.getAbsolutePath();
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);

        String url = AppConstants.SERVER_URL + UAP_BASE_URL + "SphsApp/UploadFile";
        String url1 = url.startsWith("https") ? url.replace("https", "http") : url;
        OkHttpUtils.post()
                .url(url)
//                .url("http://192.168.31.229:9001" + UAP_BASE_URL + "SphsApp/UploadFile")
                .addHeader("sessionid", ConfigUtil.getInstance().getSessionId())
                .params(params)
                .addFile("upload_file", fileName, uploadFile)
                .buildByAESEncodeParams()
                .execute(fileCallback);
    }

    /**
     * post请求发送
     *
     * @param context      上下文
     * @param context      文件id
     * @param fileCallback 回调
     */
    public static void downLoadFile(Context context, String fileId,
                                    FileCallBack fileCallback) {
        if (context == null)
            return;

        if (!Network.isAvailable(context)) {
            fileCallback.onError(null, 0, new Exception("当前无网络可用"));
            fileCallback.onAfter();
            return;
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("fileId", fileId);// 占位参数，无用
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        params.put("time", DateFormatUtil.getCurrentDate());
//        Map<String, String> requestParam = encryptRequestParam(params);
//        if (requestParam == null) {
//            fileCallback.onError(null, -2, new Exception("参数为空"));
//            return;
//        }
        String downloadUrl = SPUtil.get(AppConstants.PC_WEB, "").toString();
        OkHttpUtils.post()
                .url(downloadUrl + "/service/DownloadFile")
//                .url("http://192.168.31.229:13889" + "/service/DownloadFile")
                .addHeader("sessionid", ConfigUtil.getInstance().getSessionId())
                .params(params)
                .buildByAESEncodeParams()
                .execute(fileCallback);
    }

    public static void PauseMeeting(Context context, Map<String, String> params,
                                    StringCallback stringCallback) {
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        post("SphsApp/PauseMeeting", params, context, stringCallback);
    }

    public static void GetResourceInfoList(Context context, String locationName, StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("locationName", locationName);
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        post("SphsApp/GetMatchResourceInfo", params, context, stringCallback);
    }


    public static void getInfo(Context context, StringCallback stringCallback) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        post("SphsApp/getInfo", params, context, stringCallback);
    }

    public static void tenantSignIn(Context context, String tenantId, StringCallback getTenantCallback) {
        Map<String, String> params = new HashMap<>();
        params.put("sessionid", ConfigUtil.getInstance().getSessionId());
        params.put("tenantId", tenantId);
        post("Login/TenantSignIn", params, context, getTenantCallback);
    }


//    /**
//     * 对数据参数的数据进行加密
//     *
//     * @param params
//     * @return
//     */
//    private static Map<String, String> encryptRequestParam(Map<String, String> params) {
//        String paramStr = new Gson().toJson(params);
//        String base64Param = Base64.encodeToString(paramStr.getBytes(), Base64.NO_WRAP);
//        // Log.d(TAG, "base64Param: "+base64Param);
//        ThreeDESEncryptionUtil tripleDESEncryptionUtil = new ThreeDESEncryptionUtil();
//        String requestValue;
//        String timestamp;
//        String code3DES;
//
//        try {
//            requestValue = tripleDESEncryptionUtil.encryptThreeDESECB(paramStr, CustomerEncryption.decode(CustomerEncryption.code));
//            timestamp = tripleDESEncryptionUtil.encryptThreeDESECB(String.valueOf(System.currentTimeMillis()), CustomerEncryption.decode(CustomerEncryption.code));
//            code3DES = tripleDESEncryptionUtil.encryptThreeDESECB("ychs", CustomerEncryption.decode(CustomerEncryption.code));
//        } catch (Exception e) {
//            return null;
//        }
//        String requestKey = HashUtil.getHmacSha1(base64Param);
//        // Log.d(TAG, "hashKey: "+requestKey);
//
//        Map<String, String> requestParam = new HashMap<>();
//        requestParam.put("key", requestKey);
//        requestParam.put("value", requestValue);
//        requestParam.put("code", code3DES);
//        //   requestParam.put("timestamp", timestamp);
//        return requestParam;
//    }


}
